<template>
    <div class="wh-100 " style="background-color: white">
        <div class="w-100 bor-base-b d-flex-between-center pl-12 pr-12 ch50">
            <div class="fw-6 fs-14">用人单位白名单</div>
            <div class="d-flex-align-center">
                <Button @click="$router.go(-1)" style="background-color: white">返回</Button>
                <Button v-loading="exportingAll" @click="dropExportAll" >导出全部数据</Button>

                <Button  @click="importFormView = true">导入单位白名单</Button>
                <Modal
                    v-model="importFormView"
                    title="导入单位白名单">
                    <Form :model="importForm" :label-width="80">
                        <FormItem label="文件: ">
                            <Upload
                                accept=".xls,.xlsx"
                                :before-upload="handleUpload">
                                <Button icon="ios-cloud-upload-outline">点击上传</Button>
                            </Upload>
                            <div v-if="importForm.file !== null">
                                {{ importForm.file.name }}
                            </div>
                            <div>说明：请依据模板数据格式导入，文件格式必须为.xlsx</div>
                        </FormItem>
                    </Form>
                    <div slot="footer">
                        <Button @click="importFormcCncel">取消</Button>
                        <Button type="primary" :loading="importing" @click="importFormOk">开始上传</Button>
                    </div>
                </Modal>
                <Button @click="downloadTempleA"  type="info">下载导入模板</Button>

                <Button type="primary" @click="modalAdd = true">添加白名单</Button>
            </div>
        </div>
        <div  class="w-100 h-95 pt-12">
            <div class="w-100 h-90 mt-8 " v-loading="dataLoading" v-ref-height="refHeight">
                <Table

                    :columns="columnsWhiteList"
                    :data="dataWhiteList"
                    :height="refHeight.value"
                >
                    <template slot-scope="{ row, index }" slot="action">
                        <Button type="primary"  @click="startChecking(row)">编辑</Button>
                        <Button type="primary" v-loading="deleteLoading"  @click="deleteWhiteListData(row)">删除</Button>

                    </template>
                </Table>
            </div>
            <div class="w-100 h-5  d-flex-align-center mt-16">
                <Page
                    :total="pages.total"
                    :page-size="pages.pageSize"
                    :current="pages.pageNumber"
                    @on-change="changePage"
                    @on-page-size-change="changePageSize"
                    show-elevator
                    show-total
                    show-sizer
                    class-name="d-flex-center"
                    size="small"
                />
            </div>
        </div>
        <Modal v-model="modalAdd"
               title="添加用人单位白名单"
               width="500">
            <div class="w-100">
                <Form ref="formAdd" :model="addForm" >
                    <FormItem >
                        <Input v-model="addForm.enterpriseNames" type="textarea" :rows="4" @on-keyup="addForm.enterpriseNames=addForm.enterpriseNames.replace(/，|,|\r\n|\n|\r/g,',')"  placeholder="请填写单位名称，可以填写多个单位名称，用英文逗号（,）隔开" />
                    </FormItem>

                </Form>
            </div>
            <div slot="footer">
                <Button  @click="modalAdd = false"   >取消</Button>

                <Button  v-loading="loadingModalAdd" @click="submitAddForm"  type="primary" >确定</Button>
            </div>
        </Modal>

        <Modal v-model="modalEdit"
               title="添加用人单位白名单"
               width="500">
            <div class="w-100">
                <Form ref="formEdit" :model="editForm" :label-width="labelWidth80">
                    <FormItem label="单位名称">
                        <Input v-model="editForm.enterpriseName" type="text"   placeholder="请输入单位名称" />
                    </FormItem>
                </Form>
            </div>
            <div slot="footer">
                <Button  @click="modalEdit = false"   >取消</Button>
                <Button  v-loading="loadingModalAdd" @click="submitEditForm"  type="primary" >确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import {
    addWhiteListData,
    deleteWhiteListData, exportWhiteListData,
    getWhiteListData,
    importWhiteListData, updateWhiteListData
} from '../../api/dataVerification/dataVerification';
import { updateVal } from '../../util/ObjectUtil';

export default {
    data() {
        return {
            refHeight:{value:0},
            labelWidth80: 80,
            columnsWhiteList:[],
            columnsWhiteList_1: [
                {
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '单位名称',
                    key: 'enterpriseName'
                },
                {
                    title: '添加时间',
                    maxWidth: 200,
                    align: 'center',

                    key: 'createTime'
                },
                {
                    title: '操作',
                    maxWidth: 200,
                    align: 'center',

                    slot: 'action'
                }
            ],
            dataWhiteList: [],
            modalAdd: false,
            modalEdit: false,
            loadingModalAdd: false,
            dataLoading: false,
            deleteLoading: false,
            addForm: {
                enterpriseNames: "",
            },
            editForm: {
                id: "",
                enterpriseName: "",
            },
            pages: {
                pageSize: 10,
                pageNumber: 1,
                total: 0
            },
            importing: false,
            exportingAll: false,
            importFormView:false,
            importForm: {
                file: null,
                importMode: '1',
            },
        }
    },
    methods:{
        submitEditForm(){
            this.loadingModalAdd=true
            updateWhiteListData(this.editForm).then(res => {
                this.loadingModalAdd = false;
                this.modalEdit = false;
                this.getWhiteListData();
            })
        },
        dropExportAll() {
            this.exportingAll = true;
            exportWhiteListData().then(res => {
                this.exportingAll = false;
                // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
                const blob = new Blob([res], { type: 'charset=utf-8' });
                let url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute('download', '单位白名单.xlsx');
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); // 删除节点
                window.URL.revokeObjectURL(url); //释放该 url
            });
        },
        downloadTempleA() {
            window.location.href = process.env.BASE_URL + "单位白名单导入模板.xlsx";
        },
        async importFormOk () {
            if (this.importForm.file == null) {
                this.$Message.info('请选择文件');
                return;
            }
            let formData = new FormData();

            // formData.append('importMode', this.importForm.importMode); // 添加参数
            formData.append("file", this.importForm.file);
            this.importing = true;
            importWhiteListData(formData).then(res => {
              if (res.code === 200) {
                this.$Message.success(res.message)
              }else if (res.code === 201){
                this.$Message.success(res.message)
                const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
                const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
                // 创建临时 URL 对象
                const url = URL.createObjectURL(blob);
                const downloadLink = document.createElement('a');
                downloadLink.href = url;
                downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
                downloadLink.click();
              }else {
                this.$Message.error(res.message)
                const byteArray = Uint8Array.from(atob(res.result), c => c.charCodeAt(0));
                const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
                // 创建临时 URL 对象
                const url = URL.createObjectURL(blob);
                const downloadLink = document.createElement('a');
                downloadLink.href = url;
                downloadLink.download = '导入失败数据汇总.xlsx'; // 设置文件名
                downloadLink.click();
              }
              // this.submitLoading = false;
              this.importing = false;
              this.importFormcCncel();
              this.getWhiteListData();
            });
        },
        importFormcCncel () {
            this.importForm.file = null;
            this.importFormView = false;
        },
        // region TODO 导入档案信息 下载导入模板
        handleUpload (file) {
            const fileExt = file.name.split(".").pop().toLocaleLowerCase();
            if (!(fileExt == "xlsx" || fileExt == "xls")) {
                this.$Notice.warning({
                    title: "文件类型错误",
                    desc:
                        "所选文件‘ " +
                        file.name +
                        " ’不是EXCEL文件，请选择后缀为.xlsx或者.xls的文件。",
                });
            }else{
                this.importForm.file = file;
            }
            // this.importForm.file = file;
            return false;
        },
        deleteWhiteListData(row) {
            console.log("row",row)
            this.$Modal.confirm({
                title: "确认删除",
                render: (h) => {
                    return h('div', [
                        h('p', "您确认要删除该条数据?("+row.enterpriseName+")",),
                    ]);
                },
                loading: true,
                onOk: () => {
                    deleteWhiteListData({Id: row.id}).then(res => {
                        this.$Modal.remove();
                        this.getWhiteListData();
                    })

                }
            });





        },
        submitAddForm() {
            if(!(this.addForm.enterpriseNames.length>0)){
                this.modalAdd = false;
                return;
            }
            this.loadingModalAdd = true;
            addWhiteListData(this.addForm).then(res => {
                this.loadingModalAdd = false;
                this.modalAdd = false;
                this.addForm.enterpriseNames = "";
                this.getWhiteListData();

            })

        },
        getWhiteListData() {
            this.dataLoading = true;
            getWhiteListData(this.pages).then(res => {
                this.dataWhiteList = res.result.records;
                this.pages.total = res.result.total || 0;
                this.dataLoading = false;

            })
        },
        startChecking(row){
            // this.editForm = row;
            updateVal(this.editForm,row)
            this.modalEdit = true;
            console.log( this.editForm)
        },
        changePage: function(val) {
            this.pages.pageNumber = val;
            this.getWhiteListData();
        },
        changePageSize: function(val) {
            this.pages.pageSize = val;
            this.getWhiteListData();
        },
        onRestWindow() {
            this.columnsWhiteList =  this.restTableCellWidth(this.columnsWhiteList_1)
            this.labelWidth80 = this.searchLabelWidth(this.labelWidth80)
        },
    },
    mounted() {
        this.onRestWindow()
        window.addEventListener('resize',this.onRestWindow)
        this.getWhiteListData();
    },
    beforeDestroy() {
        window.removeEventListener('resize',this.onRestWindow)
    },
};
</script>

<style scoped lang="less">
.ch50{
    height: 50px;
}
</style>